#include "StdAfx.h"
#include "downloader_config.h"
#include "GameUtil.h"
#include <json/reader.h>
#include "StringUtil.h"
using namespace std;
void DownloaderConfig::init()
{
	string data = GetFileString("config.json");
	Json::Reader reader;	
	reader.parse(data, m_value);

	string allStocks = GetFileString(CancatPath(GetExecPath(), "all.csv"));
	vector<string> vecLines;
	FrameworkStringUtil::split(allStocks, "\n", vecLines);

	for(size_t i = 1; i < vecLines.size(); i++) {
		const string& line = vecLines[i];
		vector<string> vecFields;
		FrameworkStringUtil::split(line, ",", vecFields);

		if(!vecFields.size()) {
			continue;
		}

		string stockCode = vecFields[0];

		int extraLen = 6 - stockCode.size();

		for(int i = 0; i < extraLen; i++) {
			stockCode = "0" + stockCode;
		}		

		if(stockCode[0] == '3' || stockCode[0] == '0') {
			stockCode = "sz" + stockCode;
		} else {
			stockCode = "sh" + stockCode;
		}
		m_vecCodes.push_back(stockCode);
	}
}

void DownloaderConfig::save()
{
	string value = m_value.toStyledString();
	SaveStringToFile("config.json", value);
}

void DownloaderConfig::updateStockList( const std::string& data )
{
	SaveStringToFile(CancatPath(GetExecPath(), "all.csv"), data);
	m_vecCodes.clear();
	vector<string> vecLines;
	FrameworkStringUtil::split(data, "\n", vecLines);
	
	for(size_t i = 0; i < vecLines.size(); i++) {
		const string& line = vecLines[i];
		vector<string> vecFields;
		FrameworkStringUtil::split(line, ",", vecFields);

		if(!vecFields.size()) {
			continue;
		} 

		string stockCode = vecFields[0];

		int extraLen = 6 - stockCode.size();

		for(int i = 0; i < extraLen; i++) {
			stockCode = "0" + stockCode;
		}		

		if(stockCode[0] == '3' || stockCode[0] == '0') {
			stockCode = "sz" + stockCode;
		} else {
			stockCode = "sh" + stockCode;
		}
		m_vecCodes.push_back(stockCode);
	}
}

std::vector<std::string>& DownloaderConfig::getStockList()
{
	return m_vecCodes;
}

std::string DownloaderConfig::getStockListUpdateDate()
{
	if(!m_value.isMember("last_update")) {
		return "";
	}
	return m_value["last_update"].asString();
}
